package tmc.gui;

import java.awt.Component;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import tmc.main.TMCConstants;

import javax.swing.BoxLayout;
import javax.swing.JPanel;

import org.apache.log4j.Logger;
import org.geotools.map.DefaultMapContext;
import org.geotools.map.MapContext;

/**
 * Left menu of TMC app
 * 
 * @author Jacek
 * 
 */
public class LeftMenuView extends JPanel {

	private static Logger LOGGER = Logger.getLogger(LeftMenuView.class);

	TMCFrame parent;
	private List<LayerControlPanel> layerControlPanels;

	public LeftMenuView(TMCFrame parentFrame) {
		parent = parentFrame;
		init();
	}

	private void init() {
		LOGGER.debug("invoking init method in class LeftMenuView");
		setSize(new Dimension(TMCConstants.LEFT_MENU_VIEW_HORIZONTAL_SIZE, TMCConstants.TMC_FRAME_VERTICAL_SIZE));
		setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
		layerControlPanels = new ArrayList<LayerControlPanel>();
	}

	@Override
	public Component add(Component comp) {
		layerControlPanels.add((LayerControlPanel) comp);
		parent.getMap().addLayer(((LayerControlPanel) comp).getLayer());
		return super.add(comp);
	}

	@Override
	public void remove(Component comp) {
		layerControlPanels.remove(comp);
		parent.getMap().removeLayer(((LayerControlPanel) comp).getLayer());
		super.remove(comp);
	}

	public void moveDown(LayerControlPanel lcp) {
		MapContext map = parent.getMap();
		int pos = map.indexOf(lcp.getLayer());
		int newPos = pos - 1 >= 0 ? pos - 1 : 0;
		map.moveLayer(pos, newPos);
		Collections.swap(layerControlPanels, pos, newPos);
		reinitializeComponents();
	}

	public void moveUp(LayerControlPanel lcp) {
		MapContext map = parent.getMap();
		int pos = map.indexOf(lcp.getLayer());
		int newPos = pos + 1 <= map.getLayerCount() - 1 ? pos + 1 : map.getLayerCount() - 1;
		map.moveLayer(pos, newPos);
		Collections.swap(layerControlPanels, pos, newPos);
		reinitializeComponents();
	}

	private void reinitializeComponents() {
		removeAll();
		for (int i = layerControlPanels.size() - 1; i >= 0; i--) {
			super.add(layerControlPanels.get(i));
		}
//		for (LayerControlPanel lcp : layerControlPanels) {
//			super.add(lcp);
//		}
		revalidate();
		parent.getMapView().repaint();
	}

}
